package com.sptpc.book.service;

import com.sptpc.book.common.OrderState;
import com.sptpc.book.controller.request.NewBookRequest;
import com.sptpc.book.controller.request.NewUserRequest;
import com.sptpc.book.model.Book;
import com.sptpc.book.model.Category;
import com.sptpc.book.model.Order;
import com.sptpc.book.model.User;
import com.sptpc.book.repository.OrderRepository;
import com.sptpc.book.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private UserRepository userRepository;

    public List<Order> getOrders(String user){
        return orderRepository.findOrderByUserLike(user);
    }

    public  Order saveOrder(String user, Book... books) {
        Order order = Order.builder()
                 .user(user)
                 .items(new ArrayList<>(Arrays.asList(books)))
                .state(OrderState.INIT).build();
        return orderRepository.save(order);
    }

    public boolean changeState(Order oldOrder,OrderState state){
        if (state.compareTo(oldOrder.getState())<=0){
            log.warn("状态不能从{}到{}",oldOrder.getState(),state);
            return false;
        }
        oldOrder.setState(state);
        Order order =orderRepository.saveAndFlush(oldOrder);
        log.info("更改后的订单{}",order);
        return true;
    }

}
